// https://leetcode.cn/problems/reverse-words-in-a-string/description/?envType=study-plan-v2&envId=top-interview-150

class Solution {
public:
    string reverseWords(string s) {
        int i = 0, n = s.size();

        while (s[i] == ' ') i++;

        vector<string> words;
        string word = "";
        while (i < n) {
            if (s[i] == ' ' && word != "") {
                words.push_back(word);
                word = "";
            } else if (s[i] != ' '){
                word += s[i];
            }
            i++;
        }
        if (word != "") words.push_back(word);

        string ans = "";
        for (int j = words.size() - 1; j >= 0; j--) {
            ans += words[j];
            if (j != 0) ans += ' ';
        }
        return ans;
    }
};